package Simulator;

import java.util.HashMap;

public class FieldStats {
	@SuppressWarnings("rawtypes")
	private HashMap<Class, Counter> counters;
	private boolean countsValid;

	@SuppressWarnings("rawtypes")
	public FieldStats() {
		counters = new HashMap<Class, Counter>();
		countsValid = true;
	}

	@SuppressWarnings("rawtypes")
	public String getPopulationDetails(Field field) {
		StringBuffer buffer = new StringBuffer();
		if (!countsValid) {
			generateCounts(field);
		}
		for (Class key : counters.keySet()) {
			Counter info = counters.get(key);
			buffer.append(info.getName().substring(10));
			buffer.append(": ");
			buffer.append(info.getCount());
			buffer.append(' ');
		}
		return buffer.toString();
	}

	@SuppressWarnings("rawtypes")
	public HashMap<Class, Counter> getPopulationInfo() {
		return counters;
	}

	@SuppressWarnings("rawtypes")
	public void reset() {
		countsValid = false;
		for (Class key : counters.keySet()) {
			Counter count = counters.get(key);
			count.reset();
		}
	}

	@SuppressWarnings("rawtypes")
	public void incrementCount(Class actorClass) {
		Counter count = counters.get(actorClass);
		if (count == null) {
			count = new Counter(actorClass.getName());
			counters.put(actorClass, count);
		}
		count.increment();
	}

	public void countFinished() {
		countsValid = true;
	}

	@SuppressWarnings("rawtypes")
	public boolean isViable(Field field) {
		// How many counts are non-zero.
		int nonZero = 0;
		if (!countsValid) {
			generateCounts(field);
		}
		for (Class key : counters.keySet()) {
			Counter info = counters.get(key);
			if (info.getCount() > 0) {
				nonZero++;
			}
		}
		return nonZero > 1;
	}

	private void generateCounts(Field field) {
		reset();
		for (int row = 0; row < field.getDepth(); row++) {
			for (int col = 0; col < field.getWidth(); col++) {
				ActorInterface actor = field.getActorAt(row, col);
				if (actor != null) {
					incrementCount(actor.getClass());
				}
			}
		}
		countsValid = true;
	}
}
